using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.IO;
using OpenMTS.Properties;

namespace OpenMTS
{
    public partial class Preferences : Form
    {
        #region PROPERTIES
        private string sCurrRuleset = "";
        private string sCurrReportTemplate = "";
        private char[] seps = { '\\' };
        private ListViewColumnSorter lvwColumnSorter = null;
        #endregion

        #region CONSTRUCTORS
        public Preferences()
        {
            InitializeComponent();
        }
        #endregion

        #region EVENTS
        private void btnLoadSchemaFile_Click(object sender, EventArgs e)
        {
            string sSchemas = ConfigurationManager.AppSettings["SchemaLocation"];
            if (!sSchemas.EndsWith("\\"))
                sSchemas = sSchemas + "\\";

            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "Schema files (*.xsd)|*.xsd|All files (*.*)|*.*";
            DialogResult result = dlg.ShowDialog();
            if (result == DialogResult.OK)
            {

                string[] spieces = dlg.FileName.Split(seps);
                string sFile = spieces[spieces.Length - 1];
                string sFileAndPath = sSchemas + sFile;
                if (File.Exists(sFileAndPath))
                {

                    DialogResult dr = MessageBox.Show(
                        string.Format("Are you sure you wish to overwrite the existing file: {0}", sFile),
                        "Overwrite?", MessageBoxButtons.YesNo);
                    if (dr == DialogResult.No) return;
                }

                System.IO.File.Copy(dlg.FileName, sFileAndPath, true);
                loadSchemaList();

            }
        }

        private void btnLoadRuleFile_Click(object sender, EventArgs e)
        {   
            string sRules = ConfigurationManager.AppSettings["RulesetLocation"];
            if(!sRules.EndsWith("\\"))
                sRules = sRules + "\\";

            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "Xml files (*.xml)|*.xml|All files (*.*)|*.*";
            DialogResult result = dlg.ShowDialog();
            if (result == DialogResult.OK)
            {
                
                string[] spieces = dlg.FileName.Split(seps);
                string sFile = spieces[spieces.Length - 1];
                string sFileAndPath = sRules + sFile;
                if (File.Exists(sFileAndPath))
                {

                    DialogResult dr = MessageBox.Show(
                        string.Format("Are you sure you wish to overwrite the existing file: {0}", sFile),
                        "Overwrite?", MessageBoxButtons.YesNo);
                    if (dr == DialogResult.No) return;
                }
                System.IO.File.Copy(dlg.FileName, sFileAndPath, true);
                sCurrRuleset = sFile;
                loadRulesetCombo();
                
            }
        }

        private void Preferences_Load(object sender, EventArgs e)
        {
            lvwColumnSorter = new ListViewColumnSorter();
            this.lstSchemas.ListViewItemSorter = lvwColumnSorter;

            lstSchemas.Columns.Add("File", 300, HorizontalAlignment.Left);
            lstSchemas.Columns.Add("Date\\Time", 100, HorizontalAlignment.Left);
            
            if (Settings.Default.RulesetFile != null)
            {
                // Remove any pathing that might be around the file name
                //This is from a previous version
                sCurrRuleset = Settings.Default.RulesetFile;
                string[] spieces = sCurrRuleset.Split(seps);
                sCurrRuleset = spieces[spieces.Length - 1];
            }

            if (Settings.Default.ReportTemplate != null)
            {
                sCurrReportTemplate = Settings.Default.ReportTemplate;
                string[] spieces = sCurrReportTemplate.Split(seps);
                sCurrReportTemplate = spieces[spieces.Length - 1];
            }

            
            loadSchemaList();
            loadRulesetCombo();
            loadReportCombo();

           
        }
        

        
        private void btnOK_Click(object sender, EventArgs e)
        {  
            Settings.Default.Save();
            this.Close();
        }

        private void cmbRuleSets_SelectedIndexChanged(object sender, EventArgs e)
        {
            sCurrRuleset = cmbRuleSets.SelectedItem.ToString();
            Settings.Default.RulesetFile = sCurrRuleset;
            
        }

        private void lstSchemas_ColumnClick(object sender, ColumnClickEventArgs e)
        {   
            if (e.Column == lvwColumnSorter.SortColumn)
            {
                // Reverse the current sort direction for this column.
                if (lvwColumnSorter.Order == SortOrder.Ascending)
                {
                    lvwColumnSorter.Order = SortOrder.Descending;
                }
                else
                {
                    lvwColumnSorter.Order = SortOrder.Ascending;
                }
            }
            else
            {
                // Set the column number that is to be sorted; default to ascending.
                lvwColumnSorter.SortColumn = e.Column;
                lvwColumnSorter.Order = SortOrder.Ascending;
            }

            // Perform the sort with these new sort options.
            this.lstSchemas.Sort();

        }

        private void cmbReportTemplate_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.sCurrReportTemplate = this.cmbReportTemplate.SelectedItem.ToString();
            Settings.Default.ReportTemplate = sCurrReportTemplate;
        }

        private void btnReportTemplate_Click(object sender, EventArgs e)
        {
            string sRules = ConfigurationManager.AppSettings["ReportLocation"];
            if (!sRules.EndsWith("\\"))
                sRules = sRules + "\\";

            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "Xslt files (*.xslt)|*.xslt|All files (*.*)|*.*";
            DialogResult result = dlg.ShowDialog();
            if (result == DialogResult.OK)
            {

                string[] spieces = dlg.FileName.Split(seps);
                string sFile = spieces[spieces.Length - 1];
                string sFileAndPath = sRules + sFile;
                if (File.Exists(sFileAndPath))
                {

                    DialogResult dr = MessageBox.Show(
                        string.Format("Are you sure you wish to overwrite the existing file: {0}", sFile),
                        "Overwrite?", MessageBoxButtons.YesNo);
                    if (dr == DialogResult.No) return;
                }
                System.IO.File.Copy(dlg.FileName, sFileAndPath, true);
                loadReportCombo();

            }
        }
        #endregion

        #region METHODS

        private void loadCombo(string sAppLocation, string sSelectItem, ComboBox comboBox)
        {
            comboBox.Items.Clear();
            comboBox.Text = "";
            string sCachePath = ConfigurationManager.AppSettings[sAppLocation];
            string[] sFilesWithPath = System.IO.Directory.GetFiles(sCachePath, "*.*");

            foreach (string sFileWithPath in sFilesWithPath)
            {
                string[] spieces = sFileWithPath.Split(seps);
                string sFile = spieces[spieces.Length - 1];
                DateTime dt = File.GetCreationTime(sFileWithPath);
               
              //  int iItem = comboBox.Items.Add(string.Format("{0}({1})",sFile,dt.ToString()));
                int iItem = comboBox.Items.Add( sFile);
                if (sFile == sSelectItem)
                {
                    comboBox.SelectedIndex = iItem;
                   
                }
            }
            //Select the first item if there is no other default
            if (comboBox.SelectedIndex == -1)
                comboBox.SelectedIndex = 0;

        }

        private void loadRulesetCombo()
        {
            loadCombo("RulesetLocation", sCurrRuleset, cmbRuleSets);
        }


        private void loadReportCombo()
        {
            loadCombo("ReportLocation", sCurrReportTemplate, cmbReportTemplate);
        }

        private void loadSchemaList()
        {
            lstSchemas.Items.Clear();

            string sSchemas = ConfigurationManager.AppSettings["SchemaLocation"];
            string[] schemas = System.IO.Directory.GetFiles(sSchemas, "*.*");
            foreach (string s in schemas)
            {
                DateTime dt = File.GetCreationTime(s);
                string[] spieces = s.Split(seps);
                string[] sData = new string[] { spieces[spieces.Length - 1], dt.ToString() };

                lstSchemas.Items.Add(new ListViewItem(sData));

            }
        }
        #endregion
    
    }

    internal  class ListViewColumnSorter : IComparer
    {
        /// <summary>
        /// Specifies the column to be sorted
        /// </summary>
        private int ColumnToSort;
        /// <summary>
        /// Specifies the order in which to sort (i.e. 'Ascending').
        /// </summary>
        private SortOrder OrderOfSort;
        /// <summary>
        /// Case insensitive comparer object
        /// </summary>
        private CaseInsensitiveComparer ObjectCompare;

        /// <summary>
        /// Class constructor.  Initializes various elements
        /// </summary>
        public ListViewColumnSorter()
        {
            // Initialize the column to '0'
            ColumnToSort = 0;

            // Initialize the sort order to 'none'
            OrderOfSort = SortOrder.None;

            // Initialize the CaseInsensitiveComparer object
            ObjectCompare = new CaseInsensitiveComparer();
        }

        /// <summary>
        /// This method is inherited from the IComparer interface.  It compares the two objects passed using a case insensitive comparison.
        /// </summary>
        /// <param name="x">First object to be compared</param>
        /// <param name="y">Second object to be compared</param>
        /// <returns>The result of the comparison. "0" if equal, negative if 'x' is less than 'y' and positive if 'x' is greater than 'y'</returns>
        public int Compare(object x, object y)
        {
            int compareResult;
            ListViewItem listviewX, listviewY;

            // Cast the objects to be compared to ListViewItem objects
            listviewX = (ListViewItem)x;
            listviewY = (ListViewItem)y;

            // Compare the two items
            compareResult = ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text, listviewY.SubItems[ColumnToSort].Text);

            // Calculate correct return value based on object comparison
            if (OrderOfSort == SortOrder.Ascending)
            {
                // Ascending sort is selected, return normal result of compare operation
                return compareResult;
            }
            else if (OrderOfSort == SortOrder.Descending)
            {
                // Descending sort is selected, return negative result of compare operation
                return (-compareResult);
            }
            else
            {
                // Return '0' to indicate they are equal
                return 0;
            }
        }

        /// <summary>
        /// Gets or sets the number of the column to which to apply the sorting operation (Defaults to '0').
        /// </summary>
        public int SortColumn
        {
            set
            {
                ColumnToSort = value;
            }
            get
            {
                return ColumnToSort;
            }
        }

        /// <summary>
        /// Gets or sets the order of sorting to apply (for example, 'Ascending' or 'Descending').
        /// </summary>
        public SortOrder Order
        {
            set
            {
                OrderOfSort = value;
            }
            get
            {
                return OrderOfSort;
            }
        }

    }



}